{# 新建文件：templates/model/train.html #}
<!DOCTYPE html>
<html>
<head>
    <title>模型训练中心</title>
    <meta charset="utf-8">
    {% include 'system/common/header.html' %}
</head>
<body class="pear-admin">
<div class="layui-fluid">
    <!-- 参数配置卡片 -->
    <div class="layui-card">
        <div class="layui-card-header">
            <i class="layui-icon layui-icon-set"></i> 训练参数配置
        </div>
        <div class="layui-card-body">
            <form class="layui-form" lay-filter="train-form">
                <div class="layui-form-item">
                    <label class="layui-form-label">模型类型</label>
                    <div class="layui-input-block">
                        <select name="modelType" lay-verify="required">
                            <option value="">请选择模型</option>
                            <option value="lstm">逻辑回归</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">预测年数</label>
                    <div class="layui-input-inline">
                        <input type="number" step="5" name="learningRate" value="5"
                               class="layui-input" lay-verify="required|number">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="start-train" type="button"> 开始预测</button>
                        {#                        <button class="layui-btn" lay-submit lay-filter="start-train">#}
                        {#                            <i class="layui-icon layui-icon-play"></i> #}

                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 训练可视化区域 -->
    <div class="layui-row layui-col-space15">
        <!-- 训练进度 -->
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="layui-icon layui-icon-chart"></i> 预测结果
                </div>
                <div class="layui-card-body">
                    <div id="progress-container">
                        <div id="yuche"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 结果图表 -->
        <div class="layui-col-md6">
            <div class="layui-card">
                <div class="layui-card-header">
                    <i class="layui-icon layui-icon-chart-screen"></i> 训练指标
                </div>
                <div class="layui-card-body">
                    <div id="metrics-chart" style="height: 300px;"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="{{ url_for('static', filename='system/component/layui/layui.js') }}"></script>
<script type="text/javascript" src="/static/bigscreen/static/js/echarts.min.js"></script>
<script src="{{ url_for('static', filename='/system/component/pear/module/tinymce/tinymce/plugins/kityformula-editor/kityformula/js/jquery-3.6.0.min.js') }}"></script>
<script>
    var chartDom = document.getElementById('yuche');
    var myChart = echarts.init(chartDom);
    var option;
    option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: []
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: []
    };
    option && myChart.setOption(option);


</script>


<script>
    layui.use(['form', 'layer'], function () {
        var form = layui.form;
        var layer = layui.layer;

        // 表单提交监听
        form.on('submit(start-train)', function (data) {
            // 1. 获取表单数据
            var formData = data.field;
            // 2. 发送 AJAX 请求（示例使用 jQuery）
            $.ajax({
                url: '/module/train', // 替换为你的后端接口
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                    {#model_type: formData.modelType,#}
                    predict_years: formData.learningRate
                }),
                success: function (res) {
                    layer.msg('预测任务已启动');

                    // 2. 提取核心数据
                    console.log(res);


                    const trainingData = res.data.training_data; // 历史训练数据
                    const predictions = res.data.predictions;    // 预测数据
                    const modelInfo = res.data.model_info;       // 模型参数

                    // 3. 数据格式转换（示例处理 yield 产量）
                    const processData = (dataArray) => {
                        return dataArray.map(item => ({
                            year: Number(item.year),
                            yield: Number(item.yield).toFixed(2),
                            affected: Number(item.affected).toFixed(2),
                            planting: Number(item.planting).toFixed(2)
                        }));
                    };

                    // 4. 合并历史与预测数据（用于完整时间轴）
                    const allYearsData = [...processData(trainingData), ...processData(predictions)];

                    // 5. ECharts 配置更新（示例显示 yield 趋势）
                    const chartOption = {
                        tooltip: {
                            trigger: 'axis',
                            formatter: function (params) {
                                let html = params[0].axisValue + '<br>';
                                params.forEach(item => {
                                    // 过滤空值显示
                                    if (item.value !== null) {
                                        // 判断是否是历史数据部分
                                        const isHistorical = item.dataIndex < trainingData.length;
                                        // 只显示对应的历史或预测标签
                                        if ((isHistorical && !item.seriesName.includes('预测')) || 
                                            (!isHistorical && item.seriesName.includes('预测'))) {
                                            html += `${item.marker} ${item.seriesName}: ${item.value}<br>`;
                                        }
                                    }
                                });
                                return html;
                            }
                        },
                        legend: {
                            data: ['历史产量', '预测产量', '历史受灾面积', '预测受灾面积', '历史播种面积', '预测播种面积']
                        },
                        grid: {left: '3%', right: '4%', bottom: '12%', containLabel: true},
                        xAxis: {
                            type: 'category',
                            data: allYearsData.map(d => d.year)
                        },
                        yAxis: {type: 'value'},
                        series: [
                            // 产量系列
                            {
                                name: '历史产量',
                                data: trainingData.map(d => d.yield),
                                type: 'line',
                                smooth: true,
                                itemStyle: {color: '#5470c6'}
                            },
                            {
                                name: '预测产量',
                                data: [...new Array(trainingData.length).fill(null), ...predictions.map(d => d.yield)],
                                type: 'line',
                                lineStyle: {type: 'dashed', color: '#5470c6'},
                                symbol: 'triangle',
                                itemStyle: {color: '#5470c6'}
                            },

                            // 受灾面积系列
                            {
                                name: '历史受灾面积',
                                data: trainingData.map(d => d.affected),
                                type: 'line',
                                smooth: true,
                                yAxisIndex: 0,
                                itemStyle: {color: '#ee6666'}
                            },
                            {
                                name: '预测受灾面积',
                                data: [...new Array(trainingData.length).fill(null), ...predictions.map(d => d.affected)],
                                type: 'line',
                                lineStyle: {type: 'dashed', color: '#ee6666'},
                                symbol: 'rect',
                                itemStyle: {color: '#ee6666'}
                            },

                            // 播种面积系列
                            {
                                name: '历史播种面积',
                                data: trainingData.map(d => d.planting),
                                type: 'line',
                                smooth: true,
                                yAxisIndex: 0,
                                itemStyle: {color: '#73c0de'}
                            },
                            {
                                name: '预测播种面积',
                                data: [...new Array(trainingData.length).fill(null), ...predictions.map(d => d.planting)],
                                type: 'line',
                                lineStyle: {type: 'dashed', color: '#73c0de'},
                                symbol: 'diamond',
                                itemStyle: {color: '#73c0de'}
                            }
                        ]
                    };

                    // 6. 渲染图表（假设已初始化 myChart）
                    myChart.setOption(chartOption);

                    const metricsHtml = `  <div class="layui-row layui-col-space10">
                        <div class="layui-col-md6">
                          <table class="layui-table">
                            <colgroup><col width="50%"><col width="50%"></colgroup>
                            <thead><tr><th colspan="2" style="text-align: center">特征权重</th></tr></thead>
                            <tbody>
                              ${Object.entries(modelInfo.coefficients).map(([name, value]) => `            <tr><td>${name}</td><td>${value.toFixed(2)}</td></tr>
                              `).join('')}        </tbody>
                          </table>
                        </div>
                        <div class="layui-col-md6">
                          <table class="layui-table">
                            <colgroup><col width="60%"><col width="40%"></colgroup>
                            <thead><tr><th colspan="2" style="text-align: center">模型评估</th></tr></thead>
                            <tbody>
                              <tr><td>平均绝对误差 (MAE)</td><td>${modelInfo.metrics.mae.toFixed(2)}</td></tr>
                              <tr><td>均方误差 (MSE)</td><td>${modelInfo.metrics.mse.toFixed(2)}</td></tr>
                              <tr><td>R²得分</td><td>${modelInfo.metrics.r2_score.toFixed(4)}</td></tr>
                              <tr><td>模型截距</td><td>${modelInfo.intercept.toFixed(2)}</td></tr>
                            </tbody>
                          </table>
                        </div>
                      </div>`;

                    // 更新指标区域（替换原有图表）
                                        $('#metrics-chart').html(metricsHtml).css('height', 'auto'); // 移除固定高度


                },
                error: function (err) {
                    layer.msg('请求失败: ' + err.responseText);
                }
            });
            return false; // 阻止表单默认提交
        });
    });

</script>
<style>
    #yuche {
        height: 400px; /* 必须定义高度 */
        width: 80%; /* 需要定义宽度 */
        min-width: 500px; /* 防止内容挤压 */
    }

</style>
</body>
</html>
